import * as fs from "fs";
import { resolve, join, dirname } from "path";
import express from "express";
import { loadEnv } from "vite";
import http from "http";
import { fileURLToPath } from "url";

// const serverStatic = require('serve-static')
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const client = resolve(root, "./client");
const server = resolve(root, "./server");
console.log({ root });

// use vite's connect instance as middleware
// server.use(serverStatic(client, { index: false }))
const template = fs.readFileSync(resolve(client, "index.html"), "utf-8");
http
  .createServer(async (req, res) => {
    try {
      const url = req.url;
      const { render } = await import(resolve(server, "./entry-server.js"));
      const manifest = await import(
        resolve(client, "./.vite/ssr-manifest.json"),
        { assert: { type: "json" } }
      );

      const ctx = {};
      const html = await render(url, manifest, ctx, template, client);
      res.setHeader("Content-Type", "text/html");
      res.end(html);
    } catch (e) {
      console.error(e);
      res.set({ "Content-Type": "text/html" }).end(template);
    }
  })
  .listen(9020, () => {
    console.log("look at http://localhost:9020");
  });
